package gw.com.android.ui;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Base64;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.FrameLayout;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.gwtsz.gts2.hx.BuildConfig;
import com.gwtsz.gts2.hx.R;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tendcloud.appcpa.TalkingDataAppCpa;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.app.dispatch.AppDispatch;
import gw.com.android.model.ConfigSettingDeal;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.presenter.LoginPresenter;
import gw.com.android.presenter.MegLive;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.dialog.LoginDialog;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.ui.dialog.PopupDoubleBtnDialog;
import gw.com.android.ui.dialog.SelectPhotoPopWindow;
import gw.com.android.ui.dialog.SharePopWindow;
import gw.com.android.ui.me.FeedbackActivity;
import gw.com.android.ui.views.AccountLockingView;
import gw.com.android.ui.views.CommonTitleBar;
import gw.com.android.utils.ChannelUtil;
import gw.com.android.utils.ENV;
import gw.com.android.utils.ImageUtil;
import gw.com.android.utils.PermissionTool;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.AppActivities;
import www.com.library.app.Logger;
import www.com.library.app.ObjectSessionStore;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.model.DataItemDetail;
import www.com.library.util.AESCrypto;
import www.com.library.util.CommonUtils;
import www.com.library.util.DeviceUtil;
import www.com.library.util.FileUtil;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.PermissionUtil;
import www.com.library.view.BtnClickListener;
import www.com.library.view.RecyclerClickListener;
import www.com.library.view.X5WebView;

/**
 * 项目中嵌套网页显示的界面
 */
public class WebFragment extends PushMsgTabFragment implements PlatformActionListener {

    private final String TAG = "WebFragment";
    private boolean isFirstStartOcr = true;
    private static final int REQUEST_CODE_CAMERA = 102;
    private static final int REQUEST_CODE_BANKCARD = 110;
    public static final int REQUEST_CODE_MEGLIVE = 116;
    /**
     * 身份证正面
     */
    private static final int CONTENT_TYPE_ID_CARD_FRONT = 1;
    /**
     * 身份证反面
     */
    private static final int CONTENT_TYPE_ID_CARD_BACK = 2;
    /**
     * 银行卡
     */
    private static final int CONTENT_TYPE_BANK_CARD = 3;
    @BindView(R.id.main_tab_title_bar)
    CommonTitleBar mTitleBar;

    @BindView(R.id.loading_progress_view)
    View mProgressView;
    @BindView(R.id.error_layout)
    View mErrorView;
    @BindView(R.id.locking_tips_layout)
    AccountLockingView mAccountLockingView;
    @BindView(R.id.webview)
    protected X5WebView mWebView;
    /**
     * 嵌入页面的URL地址
     */
    protected String url;
    /**
     * 进度条
     */
    protected String key;
    private String takePhotoPath;
    public DataItemDetail mItem;
    private boolean hasTitle = false;//界面是否需要title栏标识 true需要，false不需要
    private String title = "";//界面中间title

    private ValueCallback<Uri> mUploadMsg;
    public ValueCallback<Uri[]> mUploadMsgForAndroid5;

    private PermissionUtil mAccessCameraPermission;
    private SelectPhotoPopWindow mTakePhotoView;//拍照功能弹层
    private SharePopWindow mSharePopwindow;//分享功能弹层
    /**
     * ocr 是否被调用
     */
    private boolean isOcr = false;

    public WebFragment() {

    }

    public static WebFragment newInstance() {
        WebFragment fragment = new WebFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            url = getArguments().getString("url");
            key = getArguments().getString(ConfigType.CONFIG_TYPE_KEY_TAG);
            title = getArguments().getString(ConfigType.CONFIG_TYPE_TITLE_TAG);
            mItem = getArguments().getParcelable("item");
            hasTitle = getArguments().getBoolean("hasTitle");
        }
        //ShareSDK.initSDK(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return mRootView;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_sys_webview;
    }

    @Override
    protected void initLayoutView() {
        ButterKnife.bind(this, mRootView);
        if (hasTitle) {
            mTitleBar.setAppTitle(title);
            mTitleBar.setRightIcon(R.mipmap.a_nav_refresh);
            mTitleBar.setBtnClickListener(new BtnClickListener() {

                @Override
                public void onBtnClick(int viewID) {
                    switch (viewID) {
                        case R.id.title_right_icon:
                            refreshView();
                            break;
                    }
                }
            });
            mTitleBar.setVisibility(View.VISIBLE);
        } else {
            mTitleBar.setVisibility(View.GONE);
        }

        mErrorView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (CommonUtils.isFastDoubleClick()) {
                    return;
                }
                refreshView();//刷新页面
            }
        });
        mAccountLockingView.setBtnClickListener(new AccountLockingView.TipsBtnClickListener() {

            @Override
            public void onBtnClick(int viewID) {
                switch (viewID) {
                    case R.id.tv_tip1:
                        DataItemDetail item = new DataItemDetail();
                        item.setStringValue(ConfigType.CONFIG_TYPE_KEY_TAG, ConfigType.FORGET_PWD_TAG);
                        item.setStringValue(ConfigType.CONFIG_TYPE_TYPE_TAG, ConfigType.CONFIG_TYPE_TYPE_URL_TAG);
                        item.setStringValue(ConfigType.CONFIG_TYPE_TITLE_TAG, AppMain.getAppString(R.string.forget_title));

                        ActivityManager.showWebPageActivity(getActivity(), item, AppMain.getAppString(R.string.btn_back));
                        break;
                    case R.id.tv_tip2:
                        ConfigSettingDeal mDeal = new ConfigSettingDeal();
                        mDeal.openQQ(getActivity());
                        break;
                }
            }
        });
        if (!NetworkMonitor.hasNetWork()) {
            mProgressView.setVisibility(View.GONE);
            mErrorView.setVisibility(View.VISIBLE);
        } else {
            mProgressView.setVisibility(View.VISIBLE);
            mErrorView.setVisibility(View.GONE);
        }
        try {
            getActivity().getWindow().setFlags(
                    android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                    android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        fixDirPath();
        x5WebviewInit();
        if (null != url && url.length() > 0) {
            if (url.contains("?")) {
                url = url + "&deviceId=" + DeviceUtil.instance().getMacAddr(getActivity()) + "&v=" + BuildConfig.VERSION_CODE + "&alias=" + GTConfig.instance().alias;
            } else {
                url = url + "?deviceId=" + DeviceUtil.instance().getMacAddr(getActivity()) + "&v=" + BuildConfig.VERSION_CODE + "&alias=" + GTConfig.instance().alias;
            }
            url = ConfigUtil.getDealStrUrl(url);
        }
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                loadView();
            }
        });
        CookieSyncManager.createInstance(getActivity());
        CookieSyncManager.getInstance().sync();
    }

    @Override
    public void onSendQuote() {
        AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCode(0));
    }

    /**
     * x5控件初始化
     */
    private void x5WebviewInit() {
        X5WebView.setSmallWebViewEnabled(true);
        mWebView.initView(mWebView);
        WebSettings webSetting = mWebView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setSavePassword(false);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(getActivity().getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(getActivity().getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(getActivity().getDir("geolocation", 0)
                .getPath());
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSetting.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        mWebView.addJavascriptInterface(this, "uiObject");

        mWebView.setWebViewClient(new WebViewClient() {
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            // 网页加载完成时调用，隐藏加载提示旋转进度条
            @Override
            public void onPageFinished(WebView view, String url) {
                onFinishedPage(url);
                super.onPageFinished(view, url);
            }


            // 网页加载失败时调用，隐藏加载提示旋转进度条
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                onErrorPage(errorCode, description, failingUrl);
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (overrideUrlLoading(url)) {
                    Logger.i(TAG, "override success..");
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
        mWebView.setWebChromeClient(new ReWebChomeClient());
    }

    /**
     * 网页加载完成
     */
    public void onFinishedPage(String url) {
        cancelTask();
        if (!isTimeOut) {
            mErrorView.setVisibility(View.GONE);
            mWebView.setVisibility(View.VISIBLE);
        }
        mProgressView.setVisibility(View.GONE);
        Logger.i(TAG, "onFinishedPage url = " + url);
    }

    /**
     * 网页加载失败
     */
    public void onErrorPage(int errorCode, String description, String failingUrl) {
        mProgressView.setVisibility(View.GONE);
        if (isResumed() && !isHidden() && getActivity() != null) {
            showToastPopWindow(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1012));
        }
        Logger.i(TAG, "onErrorPage errorCode = " + errorCode + "  description = " + description + "  failingUrl = " + failingUrl);
        mErrorView.setVisibility(View.VISIBLE);
        mWebView.setVisibility(View.GONE);
    }

    /**
     * 网页界面点击事件处理
     */
    public boolean overrideUrlLoading(String url) {
        Logger.i(TAG, "overrideUrlLoading url = " + url);
        if (url != null && url.startsWith(AppDispatch.SCHEME)) {
            AppDispatch.dispatch(getActivity(), url);
            return true;
        } else if (url != null && url.contains("tel:")) {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
            startActivity(intent);
            return true;
            //吊起QQ
        } else if (url != null && url.contains("wpa.b.qq.com")) {
            //跳转到QQ
            if (DeviceUtil.instance().isAppInstalled(getActivity(), "com.tencent.mobileqq")) {
                String qq = url.substring(url.indexOf("uin=") + 4, url.length());
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(GTConfig.INTENT_QQ.replace("00000000", qq))));
            } else {
                PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(getActivity(), 0, R.string.qq_not_found, R.string.btn_close);
                dialog.show();
            }
            return true;
            //跳转到邮箱
        } else if (url != null && url.contains("cs@gwfx.com")) {
            try {
                final String email = "cs@gwfx.com";
                Intent data = new Intent(Intent.ACTION_SENDTO);
                data.setData(Uri.parse("mailto:" + email));
                startActivity(data);
            } catch (ActivityNotFoundException exception) {
                if (isResumed() && !isHidden() && getActivity() != null) {
                    showToastPopWindow(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1012));
                }
            }
            return true;
            //点击大图不加载大图界面
        } else if (url != null && url.contains(".jpg")) {
            return true;
        } else if (url != null && url.endsWith(".apk")) {
            //下载apk
            Uri uri = Uri.parse(url);
            Intent viewIntent = new Intent(Intent.ACTION_VIEW, uri);
            WebFragment.this.startActivity(viewIntent);
            return true;

        } else if (url != null && url.contains("https://btnlogin.com/")) {
            //自动登录
            url = url.replace("https://btnlogin.com/", "");
            LoginPresenter mPresenter = new LoginPresenter(getActivity());
            mPresenter.autoLogin(url, (BaseActivity) getActivity());
            return true;
        }//修改密码自动登录  https://updatepwdlogin.com/
        else if (url != null && url.contains("https://updatepwdlogin.com/")) {
            url = url.replace("https://updatepwdlogin.com/", "");
            LoginPresenter mPresenter = new LoginPresenter(getActivity());
            mPresenter.autoLogin(url, (BaseActivity) getActivity());
            return true;
        } else if (url != null && url.contains("http://fengxiang/")) {
            if (null == mSharePopwindow) {
                mSharePopwindow = new SharePopWindow(getActivity(), AppContances.SHARE_RECOMMEND_TYPE, null, null, new RecyclerClickListener() {
                    @Override
                    public void onClick(final int position, DataItemDetail itemDetail) {
                        final String mUrl = ConfigUtil.instance().getUrlPath(ConfigType.SPECIAL_ADD_REAL_TAG);
                        Logger.e("邀请好友：url == " + mUrl);
                        mSharePopwindow.onShareFun(mSharePopwindow.getTitleId(position),
                                ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1066),
                                ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1067),
                                mUrl, WebFragment.this);
                    }
                });
            }
            mSharePopwindow.show();
            return true;
        } else if (url != null && url.contains("https://qqservice.com/")) {
            ConfigSettingDeal mDeal = new ConfigSettingDeal();
            mDeal.openQQ(getActivity(), ConfigType.QQ_SOURCE_APP);
            return true;
        } else if (url != null && url.contains("https://gologin")) {
            //跳转到登录界面
            GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_REAL);
            ActivityManager.backLogin(getActivity());
            return true;
        } else if (url != null && url.contains("https://godeposit")) {
            //跳转到存款界面
            //游客登录时弹出提示
            if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST || GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_DEMO) {
                LoginDialog.showLoginDialog(getActivity(), ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1014));
                return true;
            }
            ConfigSettingDeal mSettingDeal = new ConfigSettingDeal();
            ActivityManager.showWebPageActivity(getActivity(), mSettingDeal.getItemValue(ConfigType.DEPOSIT_TAG), AppMain.getAppString(R.string.btn_back));
            return true;
        } else if (url != null && url.contains("http://goquote/")) {

            AppActivities.getSingleton().popAllActivityExceptOne(MainActivity.class.getSimpleName());
            MainActivity mainActivity = (MainActivity) ObjectSessionStore.getObject(MainActivity.class.getSimpleName() + GTSDataListener.mainNum);
            if (null != mainActivity) {
                mainActivity.setTabFragment(ConfigType.TAB_QUOTE_TAG, "");
            }
            return true;
        } else if (url != null && url.contains("chat.gwfx.com/fxstudio")) {
            //跳转到直播界面
            MainActivity mainActivity = (MainActivity) ObjectSessionStore.getObject(MainActivity.class.getSimpleName() + GTSDataListener.mainNum);
            if (null != mainActivity) {
                mainActivity.setTabFragment(ConfigType.TAB_ONLIVE_TAG, "");
            }
            return true;
        } else if (url != null && url.contains("platformapi/startapp")) {
            try {
                //Uri uri = Uri.parse(url);
                Intent intent;
                intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                intent.addCategory("android.intent.category.BROWSABLE");
                intent.setComponent(null);
                // intent.setSelector(null);
                startActivity(intent);
            } catch (Exception ignore) {
            }
            return true;
        } else if (url != null && url.equals("https://closeself/")) {
            getActivity().finish();
            return true;
        } else if (url != null && url.equals("https://feedback/")) {
            startActivity(new Intent(getContext(), FeedbackActivity.class));
            return true;
        }

        return false;
    }

    /**
     * APP对外开放的接口，请统一使用该接口规则。。。。谢谢
     */
    @JavascriptInterface
    public void call(String param) {
        Logger.i(TAG, "call..");
        AppDispatch.dispatch(getActivity(), param);
    }

    @JavascriptInterface
    public void shareContent(final String title, final String content, final String url, final String imageUrl) {
        Logger.i(TAG, "shareContent title == " + title + ", content = " + content + ", url = " + url + ", imageUrl = " + imageUrl);
        if (getActivity() == null || getActivity().isFinishing()) {
            return;
        }
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (null == mSharePopwindow) {
                    mSharePopwindow = new SharePopWindow(getActivity(), AppContances.SHARE_PROFIT_TYPE, null, null, new RecyclerClickListener() {
                        @Override
                        public void onClick(final int position, DataItemDetail itemDetail) {
                            mSharePopwindow.onShareFun(mSharePopwindow.getTitleId(position),
                                    title,
                                    content,
                                    ConfigUtil.getDealStrUrl(url), imageUrl, WebFragment.this);
                        }
                    });
                }
                mSharePopwindow.show();
            }
        });
    }

    /**
     * 过时，不要再用了，兼容老版本，所以保留
     */
    @JavascriptInterface
    public void pushView(final int viewTag) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                AppActivities.getSingleton().popAllActivityExceptOne(MainActivity.class.getSimpleName());
                MainActivity mainActivity = (MainActivity) ObjectSessionStore.getObject(MainActivity.class.getSimpleName() + GTSDataListener.mainNum);
                if (null != mainActivity) {
                    switch (viewTag) {
                        case 0:
                            mainActivity.setTabFragment(ConfigType.TAB_HOME_TAG, "");
                            break;
                        case 1:
                            mainActivity.setTabFragment(ConfigType.TAB_QUOTE_TAG, "");
                            break;
                        case 2:
                            mainActivity.setTabFragment(ConfigType.TAB_TRADE_TAG, "");
                            break;
                        case 3:
                            mainActivity.setTabFragment(ConfigType.TAB_ONLIVE_TAG, "");
                            break;
                        case 4:
                            mainActivity.setTabFragment(ConfigType.TAB_MYSELF_TAG, "");
                            break;
                    }
                }
            }
        });
    }

    /**
     * 扫描类型 1、身份证正面  2、身份证反面  3、银行卡扫描
     */
    @JavascriptInterface
    public void startOcr(final int type) {
        Logger.i(TAG, "startOcr type = " + type);
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED && PermissionTool.isCameraCanUse()) {
            requestOcr(type);
        } else {
            if (!isFirstStartOcr && !ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA) && !PermissionTool.isCameraCanUse() && ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                //当前APP没有摄像头权限弹层，或者其他相关提示
                //权限被拒绝
                PopupDoubleBtnDialog dialog = PopupDoubleBtnDialog.newInstance(getActivity(), R.string.go_setting_content, R.string.go_setting, R.string.btn_cancel, new BtnClickListener() {
                    @Override
                    public void onBtnClick(int viewID) {
                        if (viewID == R.id.action_btn_pos) {
                            Intent intent = new Intent()
                                    .setAction("android.settings.APPLICATION_DETAILS_SETTINGS")
                                    .setData(Uri.fromParts("package",
                                            BuildConfig.APPLICATION_ID, null));
                            startActivity(intent);
                        }
                    }
                });
                dialog.show();
            } else {
                mAccessCameraPermission = new PermissionUtil();
                mAccessCameraPermission.requestPermission(this, Manifest.permission.CAMERA, AppContances.REQUEST_PERMISSION_ACCESS_CAMERA, new PermissionUtil.OnRequestPermissionResult() {
                    @Override
                    public void onGranted() {
                        if (PermissionTool.isCameraCanUse()) {
                            isFirstStartOcr = false;
                            requestOcr(type);
                        } else {
                            //当前APP没有摄像头权限弹层，或者其他相关提示
                            //权限被拒绝
                            PopupDoubleBtnDialog dialog = PopupDoubleBtnDialog.newInstance(getActivity(), R.string.go_setting_content, R.string.go_setting, R.string.btn_cancel, new BtnClickListener() {
                                @Override
                                public void onBtnClick(int viewID) {
                                    if (viewID == R.id.action_btn_pos) {
                                        Intent intent = new Intent()
                                                .setAction("android.settings.APPLICATION_DETAILS_SETTINGS")
                                                .setData(Uri.fromParts("package",
                                                        BuildConfig.APPLICATION_ID, null));
                                        startActivity(intent);
                                    }
                                }
                            });
                            dialog.show();
                        }
                    }

                    @Override
                    public void onRefused() {
                        isFirstStartOcr = false;
                    }
                });
            }
        }
    }

    @JavascriptInterface
    public void TDEvent(String userId) {
        Logger.i(TAG, "TDEvent 调用 = " + userId);
        JPushInterface.setAliasAndTags(AppMain.getApp(), userId, GTConfig.instance().getJpushTagSet(), new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {
                Logger.i(TAG, "TDEvent 调用 s = " + s + ",i=" + i);
            }
        });
        try {
            TalkingDataAppCpa.onRegister(AESCrypto.Encrypt(userId));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到相关的拍照/扫描 页面
     */
    private void requestOcr(final int type) {
        //跳转到相关的拍照/扫描 页面
        OCR.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                isOcr = true;
                String token = result.getAccessToken();
                Intent intent = new Intent(getActivity(), CameraActivity.class);
                //System.out.println("getAbsolutePath "+FileUtil.createInternalFile(getActivity(),FileUtil.ID_CARD_Z).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_NATIVE_TOKEN, OCR.getInstance().getLicense());
                intent.putExtra(CameraActivity.KEY_NATIVE_ENABLE, true);
                if (type == CONTENT_TYPE_ID_CARD_FRONT) {
                    intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, FileUtil.createInternalFile(getActivity(), FileUtil.ID_CARD_Z).getAbsolutePath());
                    intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
                    startActivityForResult(intent, REQUEST_CODE_CAMERA);
                } else if (type == CONTENT_TYPE_ID_CARD_BACK) {
                    intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, FileUtil.createInternalFile(getActivity(), FileUtil.ID_CARD_F).getAbsolutePath());
                    intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_BACK);
                    startActivityForResult(intent, REQUEST_CODE_CAMERA);
                } else if (type == CONTENT_TYPE_BANK_CARD) {
                    intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, FileUtil.createInternalFile(getActivity(), FileUtil.BankCard).getAbsolutePath());
                    intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_BANK_CARD);
                    startActivityForResult(intent, REQUEST_CODE_BANKCARD);
                }

            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
            }
        }, getActivity(), getOCRAK(), getOCRSK());
    }

    private String getOCRAK() {
        if ("com.gwtsz.gts2.ft".equals(AppMain.getApp().getPackageName())) {
            return "f5Mzt20zIZEQ4mYLynzfwWbk";
        } else if ("com.gwtsz.gts2mj2.hx".equals(AppMain.getApp().getPackageName())) {
            return "dAWTG2vGnmHjViynxi0dAXSQ";
        } else {
            return "qP3W5B0a7xc6bWw4OCNv9ZLl";
        }
    }

    private String getOCRSK() {
        if ("com.gwtsz.gts2.ft".equals(AppMain.getApp().getPackageName())) {
            return "5gjXiVjzwD7xpSxVl6ZHPTW3q6gqPs3t";
        } else if ("com.gwtsz.gts2mj2.hx".equals(AppMain.getApp().getPackageName())) {
            return "X0IGIToRG0tTDY6oADjm2XsjuY2u0bzT";
        } else {
            return "aqNj7O3zwocp7klGzeTWway6N9VvTi11";
        }
    }

    @JavascriptInterface
    public String getInfo() {
        Logger.i(TAG, "getInfo..");
        JSONObject json = new JSONObject();
        String account = DataManager.instance().mAccount.getString(GTSConst.JSON_KEY_NAME);
        int accountType = GTConfig.instance().getAccountType();
        String channel = new ChannelUtil().getChannel(AppMain.getApp());
        boolean firstLogin = true;
        if (!TextUtils.isEmpty(account)) {
            firstLogin = GTConfig.instance().getBooleanValue(account + GTConfig.PREF_LOCAL_FIRST_LOGIN, true);
        }
        boolean hasReal = GTConfig.instance().getBooleanValue(GTConfig.PREF_REAL_ACCOUNT_LOGINED, false);
        try {
            json.put("account", account);
            json.put("accountType", accountType);
            json.put("channel", channel);
            json.put("firstLogin", firstLogin);
            json.put("hasReal", hasReal);
        } catch (JSONException e) {
            Logger.e("WebFragment getInfo", e);
        }
        return json.toString();
    }

    @JavascriptInterface
    public void megLive() {
        Logger.i(TAG, "megLive..");
        Logger.i("meglive", "invoked");
        mAccessCameraPermission = new PermissionUtil();
        mAccessCameraPermission.requestPermission(this, Manifest.permission.CAMERA, AppContances.REQUEST_PERMISSION_ACCESS_CAMERA, new PermissionUtil.OnRequestPermissionResult() {
            @Override
            public void onGranted() {
                MegLive.startLiveness(WebFragment.this, new MegLive.OnMegLiveListener() {
                    @Override
                    public void onResult(boolean isSuccess, String delta, byte[] image) {
                        sendMegLiveResult(isSuccess, delta, image);
                    }
                });
            }

            @Override
            public void onRefused() {
            }
        });
    }

    private Handler mShareHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case AppContances.HANDLER_SHARE_SUCCESS:
                    showToastPopWindow(AppMain.getAppString(R.string.app_share_success));
                    mWebView.loadUrl("javascript:onShareResult('1')");
                    break;
                case AppContances.HANDLER_SHARE_CANCEL:
                    showToastPopWindow(AppMain.getAppString(R.string.app_share_cancel));
                    break;
                case AppContances.HANDLER_SHARE_FAIL:
                    showToastPopWindow(AppMain.getAppString(R.string.app_share_fail) + msg.obj);
                    mWebView.loadUrl("javascript:onShareResult('0')");
                    break;
                default:
                    break;
            }
        }

    };

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        mShareHandler.sendEmptyMessage(AppContances.HANDLER_SHARE_SUCCESS);
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        throwable.printStackTrace();
        Message msg = new Message();
        msg.what = AppContances.HANDLER_SHARE_FAIL;
        msg.obj = throwable.getMessage();
        mShareHandler.sendMessage(msg);
    }

    @Override
    public void onCancel(Platform platform, int i) {
        mShareHandler.sendEmptyMessage(AppContances.HANDLER_SHARE_CANCEL);
    }

    private class ReWebChomeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress > 70) {
                cancelTask();
                mProgressView.setVisibility(View.GONE);
                Logger.i(TAG, "onProgressChanged progress > 70,so hide progress view");
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public View getVideoLoadingProgressView() {
            FrameLayout frameLayout = new FrameLayout(getActivity());
            FrameLayout.LayoutParams param = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            frameLayout.setLayoutParams(param);
            return frameLayout;
        }

        @Override
        public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback callback) {
            if (myCallback != null) {
                myCallback.onCustomViewHidden();
                myCallback = null;
                return;
            }

            ViewGroup parent = (ViewGroup) mWebView.getParent();
            parent.removeView(mWebView);
            FrameLayout.LayoutParams param = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            param.gravity = Gravity.CENTER;
            parent.addView(view, param);
            myView = view;
            myCallback = callback;
        }

        private View myView = null;
        private IX5WebChromeClient.CustomViewCallback myCallback = null;

        public void onHideCustomView() {
            if (myView != null) {
                if (myCallback != null) {
                    myCallback.onCustomViewHidden();
                    myCallback = null;
                }

                ViewGroup parent = (ViewGroup) myView.getParent();
                parent.removeView(myView);
                parent.addView(mWebView);
                myView = null;
            }
        }

        @Override
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            //openFileChooserCallBack(uploadMsg, acceptType);
            mUploadMsg = uploadMsg;
            showSelectPhotoPopWindow();
        }


        //For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            //openFileChooserCallBack(uploadMsg, acceptType);
            mUploadMsg = uploadMsg;
            showSelectPhotoPopWindow();
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            //openFileChooserCallBack(uploadMsg, "");
            mUploadMsg = uploadMsg;
            showSelectPhotoPopWindow();
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                                         FileChooserParams fileChooserParams) {
            mUploadMsgForAndroid5 = filePathCallback;
            return showSelectPhotoPopWindow();
        }


    }

    @Override
    protected void initViewData() {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            BaseActivity activity = (BaseActivity) getActivity();
            if (null != activity) {
                activity.setTransparentBar(false);
            }
        }
    }

    /**
     * 界面处理逻辑
     * 继承改fragment的类可以重写此方法，实现自己想要的逻辑
     */
    public void loadView() {
        // 未连上网络时,气泡提示
        if (!NetworkMonitor.hasNetWork()) {
            return;
        }
        if (null != mErrorView) {
            mErrorView.setVisibility(View.GONE);
        }
        if (null != mProgressView) {
            mProgressView.setVisibility(View.VISIBLE);
        }
        initTimerTask();
        if (null != mWebView) {
            Logger.i(TAG, "load url = " + url);
            mWebView.loadUrl(url);
            mWebView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 界面刷新逻辑处理
     */
    public void refreshView() {

        loadView();
    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                switch (msg.what) {
                    case AppContances.HANDLER_TIME_OUT:
                        Logger.i(TAG, "handle timeout..");
                        isTimeOut = true;
                        cancelTask();
                        if (isResumed() && !isHidden() && getActivity() != null) {
                            showToastPopWindow(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1012));
                        }
                        mProgressView.setVisibility(View.GONE);
                        mErrorView.setVisibility(View.VISIBLE);
                        mWebView.setVisibility(View.GONE);
                        break;
                }
            } catch (Exception e) {
                Logger.e(TAG, e);
            }

        }
    };
    public Timer timer = new Timer();
    public TimerTask task;
    protected boolean isTimeOut = false;

    /**
     * 初始化定时任务(处理超时)
     */
    public void initTimerTask() {
        try {
            isTimeOut = false;
            // 初始化定时器
            task = new TimerTask() {
                @Override
                public void run() {
                    handler.sendEmptyMessage(AppContances.HANDLER_TIME_OUT);
                }
            };
            // 启动定时器,设定时间内如果没有响应,则提示超时信息
            timer.schedule(task, AppContances.WEBVIEW_TIME_OUT);
        } catch (Exception e) {
            Logger.e(TAG, e);
        }
    }

    /**
     * 取消超时定时
     */
    public void cancelTask() {
        if (null != task) {
            task.cancel();
            task = null;
        }
    }

    public boolean onBackPressed() {
        if (mWebView == null || !getUserVisibleHint() || !mWebView.canGoBack()) {
            return false;
        }
        mWebView.goBack();
        return true;
    }

    @Override
    public void onDestroy() {
        try {
            //推荐有奖需要进行分享操作
            cancelTask();
            if (null != timer) {
                timer.cancel();
                timer = null;
            }
            if (null != mWebView) {
                mWebView.setVisibility(View.GONE);
                mWebView.destroy();
                mWebView = null;
            }
            if (null != handler) {
                handler.removeCallbacksAndMessages(null);
                handler = null;
            }
            if (null != mShareHandler) {
                mShareHandler.removeCallbacksAndMessages(null);
                mShareHandler = null;
            }
            super.onDestroy();
            if (isOcr) {
                OCR.getInstance().release();
            }
        } catch (Exception e) {
            Logger.e(TAG, e);
        }
    }

    private void fixDirPath() {
        String path = ImageUtil.getDirPath();
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    private void requestCameraPermission() {
        mAccessCameraPermission = new PermissionUtil();
        mAccessCameraPermission.requestPermission(this, Manifest.permission.CAMERA, AppContances.REQUEST_PERMISSION_ACCESS_CAMERA, new PermissionUtil.OnRequestPermissionResult() {
            @Override
            public void onGranted() {
                launchCamera();
            }

            @Override
            public void onRefused() {
                restoreUploadMsg();
            }
        });
    }

    private void launchCamera() {
        try {
            takePhotoPath = ImageUtil.getNewPhotoPath();
            Intent mSourceIntent = ImageUtil.takeBigPicture(getContext(), takePhotoPath);
            startActivityForResult(mSourceIntent, AppContances.REQUEST_CODE_IMAGE_CAPTURE);
        } catch (Exception e) {
            restoreUploadMsg();
        }
    }

    private void pickAlbum() {
        try {
            Intent mSourceIntent = ImageUtil.choosePicture();
            startActivityForResult(mSourceIntent, AppContances.REQUEST_CODE_PICK_IMAGE);
        } catch (Exception e) {
            restoreUploadMsg();
        }
    }

    private boolean showSelectPhotoPopWindow() {
        if (mTakePhotoView == null) {
            mTakePhotoView = new SelectPhotoPopWindow(getActivity(), getActivity().getWindow().getDecorView());
        }
        SelectPhotoPopWindow.OnItemClickListener listener = new SelectPhotoPopWindow.OnItemClickListener() {
            @Override
            public void onCamera() {
                requestCameraPermission();
            }

            @Override
            public void onPick() {
                pickAlbum();
            }

            @Override
            public void onCancel() {
                restoreUploadMsg();
            }
        };
        mTakePhotoView.setOnItemClickListener(listener);
        mTakePhotoView.show();
        return true;
    }

    private void restoreUploadMsg() {
        if (mUploadMsg != null) {
            mUploadMsg.onReceiveValue(null);
            mUploadMsg = null;

        } else if (mUploadMsgForAndroid5 != null) {
            mUploadMsgForAndroid5.onReceiveValue(null);
            mUploadMsgForAndroid5 = null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mAccessCameraPermission != null) {
            mAccessCameraPermission.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case AppContances.REQUEST_CODE_IMAGE_CAPTURE:
            case AppContances.REQUEST_CODE_PICK_IMAGE: {
                if (resultCode != Activity.RESULT_OK) {
                    restoreUploadMsg();
                    return;
                }
                try {
                    if (mUploadMsg == null && mUploadMsgForAndroid5 == null) {
                        return;
                    }
                    String sourcePath = ImageUtil.retrievePath(getActivity(), null, data);
                    if (TextUtils.isEmpty(sourcePath) || !new File(sourcePath).exists()) {
                        sourcePath = takePhotoPath;
                        if (TextUtils.isEmpty(sourcePath) || !new File(sourcePath).exists()) {
                            takePhotoPath = null;
                            Logger.e(TAG, "sourcePath empty or not exists.");
                            break;
                        }
                    }
                    Uri uri = Uri.fromFile(new File(sourcePath));
                    if (null != mUploadMsg) {
                        mUploadMsg.onReceiveValue(uri);
                    }
                    if (null != mUploadMsgForAndroid5) {
                        mUploadMsgForAndroid5.onReceiveValue(new Uri[]{uri});
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            case REQUEST_CODE_CAMERA: {
                //身份证扫描
                if (resultCode == Activity.RESULT_OK && data != null) {
                    String contentType = data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE);
                    if (!TextUtils.isEmpty(contentType)) {
                        if (CameraActivity.CONTENT_TYPE_ID_CARD_FRONT.equals(contentType)) {
                            String filePath = FileUtil.createInternalFile(getActivity(), FileUtil.ID_CARD_Z).getAbsolutePath();
                            recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, CONTENT_TYPE_ID_CARD_FRONT, filePath);
                        } else if (CameraActivity.CONTENT_TYPE_ID_CARD_BACK.equals(contentType)) {
                            String filePath = FileUtil.createInternalFile(getActivity(), FileUtil.ID_CARD_F).getAbsolutePath();
                            recIDCard(IDCardParams.ID_CARD_SIDE_BACK, CONTENT_TYPE_ID_CARD_BACK, filePath);
                        }
                    }
                }
                break;
            }
            case REQUEST_CODE_BANKCARD:
                //银行卡扫描
                RecognizeService.recBankCard(FileUtil.createInternalFile(getActivity(), FileUtil.BankCard).getAbsolutePath(),
                        new RecognizeService.ServiceListener() {
                            @Override
                            public void onResult(String result) {
                                System.out.println("REQUEST_CODE_BANKCARD " + result);
                            }
                        });
                break;
            case REQUEST_CODE_MEGLIVE:
                if (resultCode == Activity.RESULT_OK) {
                    MegLive.handleResult(data, new MegLive.OnMegLiveListener() {
                        @Override
                        public void onResult(boolean isSuccess, String delta, byte[] image) {
                            sendMegLiveResult(isSuccess, delta, image);
                        }
                    });
                } else {
                    Logger.i("meglive", "cancel meglive... ");
                    sendMegLiveResult(false, null, null);
                }
                break;
        }
    }

    private void sendMegLiveResult(boolean isSuccess, String delta, byte[] image) {
        Logger.i("meglive", "sendMegLiveResult isSuccess = " + isSuccess);
        if (mWebView != null) {
            String file = image == null ? null : Base64.encodeToString(image, Base64.NO_WRAP);
            mWebView.loadUrl("javascript:setFaceVerifyResult(" + isSuccess + ",'" + delta + "','" + file + "')");
        }
    }

    private void recIDCard(String idCardSide, final int type, final String filePath) {
        IDCardParams param = new IDCardParams();
        param.setImageFile(new File(filePath));
        // 设置身份证正反面
        param.setIdCardSide(idCardSide);
        // 设置方向检测
        param.setDetectDirection(true);
        // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
        param.setImageQuality(20);

        OCR.getInstance().recognizeIDCard(param, new OnResultListener<IDCardResult>() {
            @Override
            public void onResult(IDCardResult result) {
                if (result != null) {
                    //System.out.println("filePath = "+filePath +" , "+ result.toString());
                    HashMap<String, String> resultHashMap = new HashMap<String, String>();
                    String resultJsonStr = "";
                    if (!TextUtils.isEmpty(result.getIdCardSide())) {
                        if (result.getIdCardSide().equals("front")) {
                            resultHashMap.put("direction", result.getDirection() + "");
                            resultHashMap.put("wordsResultNumber", result.getWordsResultNumber() + "");
                            resultHashMap.put("address", result.getAddress() + "");
                            resultHashMap.put("idNumber", result.getIdNumber().toString() + "");
                            resultHashMap.put("birthday", result.getBirthday() + "");
                            resultHashMap.put("name", result.getName() + "");
                            resultHashMap.put("gender", result.getGender() + "");
                            resultHashMap.put("ethnic", result.getEthnic() + "");
                        } else if (result.getIdCardSide().equals("back")) {
                            resultHashMap.put("signDate", result.getSignDate() + "");
                            resultHashMap.put("expiryDate", result.getExpiryDate() + "");
                            resultHashMap.put("issueAuthority", result.getIssueAuthority() + "");
                        }
                    }
                    resultJsonStr = new JSONObject(resultHashMap).toString();
                    //System.out.println("filePath = "+filePath +" , "+ resultJsonStr);
                    String fileStr = ImageUtil.bitmapToString(filePath);
                    mWebView.loadUrl("javascript:ocrResult('" + type + "','" + fileStr + "','" + resultJsonStr + "')");
                }
            }

            @Override
            public void onError(OCRError error) {
                System.out.println(error.getMessage());
                String fileStr = ImageUtil.bitmapToString(filePath);
                mWebView.loadUrl("javascript:ocrResult('" + type + "','" + fileStr + "','" + "')");
            }
        });
    }

    public static void clearCookie() {
        CookieSyncManager manager = CookieSyncManager.createInstance(AppMain.getApp());
        CookieManager instance = CookieManager.getInstance();
        //String cookie = instance.getCookie("218.253.75.149");
        //Logger.i("cookie_test", "cookie before = " + cookie);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            instance.removeSessionCookies(null);
            instance.flush();
        } else {
            instance.removeSessionCookie();
        }
        instance.setCookie(ENV.isUat() ? "218.253.75.149" : "gts2admin.hx9999.com", "");
        manager.sync();
    }

}
